<template>
  <div class="consumerAccess centerFlex column">
    <div class="topBanner">
      <a
        class="header-btn"
        href="https://www.kancloud.cn/banchengyun_yunyingzhongxin/banchengyun_zpbzzx/1097948"
        target="_blank"
      >
        <Icon type="md-bookmarks" color="red" size="20" />&nbsp帮助文档
      </a>
      <Dropdown @on-click="cancellationFn" style="margin-right:24px;margin-right:3%;color:gray;font-size:14px;font-weight:bold">
        <div class="account-wrapper">
          {{username}}
          <Icon type="ios-arrow-down"></Icon>
        </div>
        <DropdownMenu slot="list" style="width: 140px;">
          <DropdownItem name="cancellation">退出登录</DropdownItem>
          <!-- <DropdownItem name="oldEdition">返回旧版</DropdownItem> -->
        </DropdownMenu>
      </Dropdown>
    </div>
    <div class="accessCon">
      <div class="title centerFlex">欢迎使用半城云，通过以下几步授权半城云招聘</div>
      <div class="process centerFlex">
        <div class="processName" :style="step === 0?'font-weight:bold':''">1.授权认证服务号</div>
        <div class="processLine">————</div>
        <div class="processName" :style="step === 1?'font-weight:bold':''">2.授权认证小程序</div>
        <div class="processLine">————</div>
        <div class="processName" :style="step === 2?'font-weight:bold':''">3.申请微信支付</div>
        <div class="processLine">————</div>
        <div class="processName" :style="step === 3?'font-weight:bold':''">4.提交版本审核</div>
      </div>
      <div class="rowLine"></div>
      <div class="conBlock centerFlex">
        <!-- 服务号授权页 -->
        <div class="codeBlock centerFlex" v-if="step==0 && !confirmService">
          <div class="imgBlock">
            <img src="https://file.open.banchengyun.com/2019/05/07/155719256495672.png" />
            <div class="imgTip centerFlex">已认证服务号管理员扫码</div>
          </div>
          <div class="imgBlock">
            <img src="https://file.open.banchengyun.com/2019/05/15/155791030596850.png" />
            <div class="imgTip centerFlex">选择对应服务号</div>
          </div>
        </div>
        <!-- 小程序授权页 -->
        <div class="codeBlock centerFlex" v-if="step==1 && !confirmService">
          <div class="imgBlock">
            <img src="https://file.open.banchengyun.com/2019/05/07/155719256495672.png" />
            <div class="imgTip centerFlex">已认证小程序管理员扫码</div>
          </div>
          <div class="imgBlock">
            <img src="https://file.open.banchengyun.com/2019/05/15/155791126166193.png" />
            <div class="imgTip centerFlex">选择对应小程序</div>
          </div>
        </div>
        <!-- 提交版本审核页 -->
        <div class="shouquanBlock centerFlex" v-if="step==3">
          <div class="shouTitle">请确认以下信息并提交版本</div>
          <div class="banBlock centerFlex">
            <div class="banFirst">
              <div class="headImg">
                <img
                  :src="empowerRet.headImg?empowerRet.headImg:'https://file.open.banchengyun.com/2019/05/07/155719256495672.png'"
                />
              </div>
              <div class="minTitle">{{empowerRet.nickname}}</div>
              <div class="conDetail">
                公众号类型：服务号&nbsp&nbsp
                <!-- <Icon type="md-information-circle" color="red" size="18"/> -->
                <br />
                认证类型：{{empowerRet.verifyType < 0 ?'未认证':'已认证'}}
                <br />
                原始ID：{{empowerRet.userName}}
                <br />
                授权方appid：{{empowerRet.authorizerAppid}}
                <br />
              </div>
            </div>
            <div class="banSecond" style="height:100%;text-align:center;margin-left:100px">
              <div class="headImg">
                <img
                  :src="empowerRetMp.headImg?empowerRetMp.headImg:'https://file.open.banchengyun.com/2019/05/07/155719256495672.png'"
                />
              </div>
              <div class="minTitle">{{empowerRetMp.nickname}}</div>
            </div>
          </div>
          <div class="warnCon">小程序需要审核通过才能使用，提交至微信团队进行审核，约1~3个工作日</div>
          <div class="buttonBlock centerFlex">
            <Button
              class="button centerFlex"
              style="background:rgb(200,200,200);margin-right:10px"
              @click="backStep"
            >返回上一步</Button>
            <Button class="button centerFlex" @click="finishConfig">提交版本审核</Button>
            <Button class="button centerFlex" @click="loginOut">退出登陆</Button>
          </div>
        </div>
        <!-- 服务号授权页 -->
        <div class="shouquanBlock centerFlex" v-if="step==0&&confirmService">
          <div class="shouTitle">请确认授权服务号信息</div>
          <div class="headImg">
            <img :src="empowerRet.headImg" />
          </div>
          <div class="minTitle">{{empowerRet.nickName}}</div>
          <div class="conDetail">
            公众号类型：服务号&nbsp&nbsp
            <!-- <Icon type="md-information-circle" color="red" size="18"/> -->
            <br />
            认证类型：{{empowerRet.verifyType < 0 ?'未认证':'已认证'}}
            <br />
            原始ID：{{empowerRet.userName}}
            <br />
            授权方appid：{{empowerRet.authorizerAppid}}
            <br />
          </div>
          <div class="warnCon">{{empowerRet.message}}</div>
          <div class="buttonBlock centerFlex">
            <Button
              class="button errorButton centerFlex"
              @click="authorSevice"
              v-if="!empowerRet.isAvailable"
            >重新授权服务号</Button>
            <Button
              class="button errorButton centerFlex"
              @click="authorSevice"
              v-if="empowerRet.isAvailable"
              style="margin-right:10px"
            >换其它服务号重新授权</Button>
            <Button
              class="button centerFlex"
              @click="nextStep"
              v-if="empowerRet.isAvailable"
            >信息确认无误，下一步</Button>
          </div>
        </div>
        <!-- 服务号授权页 -->
        <div class="warnBlock" v-if="step==0">
          <div class="warnTitle">注意</div>
          <div class="warnCon">
            1.服务号必须已认证
            <br />2.由服务号管理员扫码授权
            <br />3.选择授权服务号
            <br />4.服务号不能授权其它第三方平台
          </div>
        </div>
        <!-- 小程序授权页 -->
        <div class="shouquanBlock centerFlex" v-if="step==1&&confirmService">
          <div class="shouTitle">请确认授权小程序信息</div>
          <div class="headImg">
            <img :src="empowerRetMp.headImg" />
          </div>
          <div class="minTitle">{{empowerRetMp.nickName}}</div>
          <div class="warnCon">{{empowerRetMp.message}}</div>
          <div class="buttonBlock centerFlex">
            <Button
              class="button errorButton centerFlex"
              @click="authorProgram"
              v-if="!empowerRetMp.isAvailable"
            >重新授权小程序</Button>
            <Button
              class="button errorButton centerFlex"
              @click="authorProgram"
              v-if="empowerRetMp.isAvailable"
              style="margin-right:10px"
            >换其它小程序重新授权</Button>
            <Button
              class="button centerFlex"
              @click="nextStep"
              v-if="empowerRetMp.isAvailable"
            >信息确认无误，下一步</Button>
          </div>
        </div>
        <!-- 小程序授权页 -->
        <div class="warnBlock" v-if="step==1">
          <div class="warnTitle">注意</div>
          <div class="warnCon">
            1.小程序必须已认证
            <br />2.由小程序管理员扫码授权
            <br />3.选择授权小程序
            <br />4.小程序主体必须与公众号、微信支付一致
            <br />5.小程序不能授权其它第三方平台
          </div>
        </div>
        <!-- 微信支付申请页 -->
        <Form
          v-if="step==2"
          style="margin-top:80px"
          ref="formValidate"
          :model="formValidate"
          :rules="ruleValidate"
          :label-width="80"
        >
          <!-- <FormItem label="半城云特约商户" prop="type" label-width="150">
            <RadioGroup v-model="formValidate.type">
              <Radio label="2">是</Radio>
              <Radio label="1">否</Radio>
            </RadioGroup>
          </FormItem>-->
          <FormItem label="微信支付商户号" prop="mch_id" label-width="150">
            <Input v-model="formValidate.mch_id" placeholder="请输入微信支付商户号" style="width:400px"></Input>
          </FormItem>
          <FormItem label="API密钥" prop="secret_key" label-width="150">
            <Input v-model="formValidate.secret_key" placeholder="请输入API密钥"></Input>
          </FormItem>
          <FormItem label="安全证书 KEY" prop="key" label-width="150">
            <div class="input-wrapper">
              <Input
                readonly
                v-model="formValidate.key"
                placeholder="点击开始上传证书"
                style="cursor: pointer;"
              ></Input>
              <input
                class="upload-input"
                name="key"
                type="file"
                accept=".pem"
                @change="handleFileChange"
              />
            </div>
          </FormItem>
          <FormItem label="安全证书 CERT" prop="cert" label-width="150">
            <div class="input-wrapper">
              <Input
                readonly
                v-model="formValidate.cert"
                placeholder="点击开始上传证书"
                style="cursor: pointer;"
              ></Input>
              <input
                class="upload-input"
                name="cert"
                type="file"
                accept=".pem"
                @change="handleFileChange"
              />
            </div>
          </FormItem>
          <FormItem style="padding:30px 0 0 100px;">
            <Button type="primary" @click="handleSubmit('formValidate')">保存并进行下一步</Button>
            <Button type="primary" @click="loginOut">退出登陆</Button>
          </FormItem>
        </Form>
      </div>
      <!-- 服务号和小程序所需 -->
      <div class="rowLine" v-if="step==0||step==1"></div>
      <!-- 服务号授权页 -->
      <div class="buttonBlock centerFlex" v-if="step==0&&!confirmService">
        <Button class="button centerFlex" @click="authorSevice">开始授权服务号</Button>
        <Button class="button centerFlex" @click="loginOut">退出登陆</Button>
      </div>
      <!-- <div class="buttonBlock centerFlex" v-if="step==0&&confirmService" @click="authorSevice">
        <Button class="button errorButton centerFlex" @click="authorSevice">换其它服务号重新授权</Button>
        <Button class="button centerFlex" @click="nextStep">信息确认无误，下一步</Button>
      </div>-->
      <!-- 小程序授权页 -->
      <div class="buttonBlock centerFlex" v-if="step==1 && !confirmService">
        <Button
          class="button centerFlex"
          style="background:rgb(200,200,200);margin-right:10px"
          @click="backStep"
        >返回上一步</Button>
        <Button class="button centerFlex" @click="authorProgram">开始授权小程序</Button>
        <Button class="button centerFlex" @click="loginOut">退出登陆</Button>
      </div>

      <!-- 弹窗 -->
      <Modal title="授权" v-model="isScan" class-name="vertical-center-modal">
        <div style="width:100%;height:350px;flex-direction:column" class="centerFlex">
          <canvas id="qr"></canvas>
          <div
            style="position:absolute;width:300px;height:300px;background:#F8F8FF;opacity:.9;margin-top:-30px"
            v-if="showMohu"
          ></div>
          <div style="font-size:12px;padding:20px 0;">{{codeTip}}</div>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
import { uploadFile } from "api/uploadFile";
import axios from "axios";
import Qrious from "qrious";
import { Resolve, SetWechatPayment, Commit } from "api/recuit/consumerAccess";
import { LoginOut } from "api/recuit/login";
import Config from "@/config";

const events = {
  WAIT_SCAN: "WAIT_SCAN", // 等待扫码
  IS_SCAN: "IS_SCAN", // 已扫码
  IS_EXPIRED: "IS_EXPIRED", // 已失效
  IS_EMPOWER: "IS_EMPOWER", // 已授权
  CLOSE_WAIT: "CLOSE_WAIT" // 连接关闭
};

export default {
  name: "consumerAccess",
  data() {
    return {
      step: 0, //执行步骤
      username: localStorage.getItem("username"), //登陆账号
      isScan: false, //弹窗扫码
      confirmService: false, //是否展示服务号界面
      codeTip: "请扫描二维码进行授权",
      showMohu: false, //是否模糊二维码
      formValidate: {
        mch_id: "",
        type: 2,
        secret_key: "",
        key: "",
        cert: ""
      },
      ruleValidate: {
        mch_id: [
          {
            required: true,
            message: "微信支付商户号不得为空",
            trigger: "blur"
          }
        ],
        secret_key: [
          {
            required: true,
            message: "API密钥不得为空",
            trigger: "blur"
          }
        ],
        type: [
          { required: true, message: "请选择是否是特约商户", trigger: "change" }
        ],
        key: [
          {
            required: true,
            message: "安全证书 KEY不得为空",
            trigger: "blur"
          }
        ],
        cert: [
          {
            required: true,
            message: "安全证书 CERT不得为空",
            trigger: "blur"
          }
        ]
      },
      formData: new FormData(),

      //扫码授权
      ...events,
      type: "MP",
      codeStep: events.WAIT_SCAN,
      QR: "",
      token: "",
      funcs: [],
      empowerRet: {
        isAvailable: false,
        message: "",
        headImg: "",
        nickName: "",
        authorizerAppid: "",
        verifyType: -1,
        username: ""
      },
      empowerRetMp: {
        isAvailable: false,
        message: "",
        headImg: "",
        nickName: ""
      }
    };
  },
  components: {},
  mounted() {
    let url = document.location.toString();
    let temp = url.split("?")[1];
    if (temp.split("=")[0] == "step") {
      this.step = Number(temp.split("=")[1]);
    } else {
      this.step = this.$route.params.step;
    }
  },
  watch: {
    QR() {
      new Qrious({
        element: document.getElementById("qr"),
        value: this.QR,
        size: 300
      });
    }
  },
  methods: {
    handleFileChange(event) {
      this.spinShow = true;
      let formData = this.formData;
      formData.append([event.target.name], event.target.files[0]);
      this.formValidate[event.target.name] = event.target.name + ".pem";
    },
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          var formData = new FormData();
          formData.append("mch_id", this.formValidate.mch_id);
          formData.append("type", 1);
          formData.append("secret_key", this.formValidate.secret_key);
          formData.append("key", this.formData.get("key"));
          formData.append("cert", this.formData.get("cert"));
          axios
            .post(`${Config.recuitUrl}/empower/setWechatPayment`, formData, {
              // 单独配置
              withCredentials: true,
              headers: {
                "Content-Type": "multipart/form-data"
              }
            })
            .then(res => {
              this.$Message.success("Success!");
              let step = this.step;
              this.step = ++step;
            })
            .catch(err => {
              this.$Message.error(err);
            });
        } else {
          this.$Message.error("Fail!");
        }
      });
    },
    //完成配置
    finishConfig() {
      Commit();
      this.$Message.success("已完成配置");
      setTimeout(() => {
        this.$router.replace("/survey/surveyContent");
      }, 1500);
    },
    // 上一步
    backStep() {
      let step = this.step;
      this.step = --step;
    },
    //下一步
    nextStep() {
      let step = this.step;
      this.confirmService = false;
      this.step = ++step;
      Resolve();
    },
    //开始授权服务号
    authorSevice() {
      this.showMohu = false;
      this.codeTip = "请扫码授权服务号";
      this.isScan = true;
      this.startAuthor("OA");
    },
    //开始授权小程序
    authorProgram() {
      this.showMohu = false;
      this.codeTip = "请扫码授权小程序";
      this.isScan = true;
      this.startAuthor("MP");
    },
    loginOut() {
      this.$router.replace("/login");
      LoginOut();
    },
    // 授权请求发起
    async startAuthor(type) {
      try {
        let {
          data: {
            data: { url, token },
            status
          }
        } = await axios({
          withCredentials: true,
          url: `${Config.recuitUrl}/empower/start/${type}`
        });

        if (status == "no-login") {
          this.$Message.error("登陆状态失效，请重新登陆");
          setTimeout(() => {
            this.$router.replace("/login");
          }, 1500);
        }

        this.QR = url; // 二维码URL
        this.token = token; // 长连接Token
        // 浏览器刷新/关闭时断开长连接
        window.addEventListener("beforeunload", () => this.closeWait(token));
        // 进行第一阶段阻塞(等待用户扫码)
        let { funcs } = await this.wait();
        // this.$set(this, 'funcs', funcs)
        this.funcs = funcs;
        // this.$set(this, 'codeTip', ("请选择账号，勾选以下权限：" + funcs.join()))
        this.codeTip = "请选择账号，勾选以下权限：" + funcs.join();
        // this.$set(this, 'showMohu', true)
        this.showMohu = true;

        await this.wait().then(res => {
          if (type == "OA") {
            this.empowerRet = res;
          } else if (type == "MP") {
            this.empowerRetMp = res;
          }
          this.isScan = false;
          this.confirmService = true;
        });
      } catch (ex) {
        this.closeWait();
      }
    },
    closeWait() {
      if (this.token) {
        axios(`${Config.recuitUrl}/empower/closeWait/${this.token}`);
        this.token = null;
      }
    },
    wait() {
      return axios(`${Config.recuitUrl}/empower/wait/${this.token}`).then(
        ({ data: { data } }) => {
          let { event } = data;
          let { IS_EXPIRED, CLOSE_WAIT } = events;

          this.codeStep = event;

          if ([IS_EXPIRED, CLOSE_WAIT].includes(event)) {
            this.token = null;
            // this.showMohu = true
            return Promise.reject(event);
          } else {
            return Promise.resolve(data);
          }
        }
      );
    },
    // 注销登陆
    cancellationFn(_name) {
      // 注销
      switch (_name) {
        case "cancellation":
          LoginOut();
          this.$router.replace("/login");
          break;
      }
    }
  }
};
</script>

<style scoped lang="less">
.centerFlex {
  display: flex;
  align-items: center;
  justify-content: center;
}
.column {
  flex-direction: column;
}
.button {
  height: 35px;
  border-radius: 5px;
  background: rgb(38, 119, 213);
  color: white;
  padding: 0 10px;
  margin-right: 10px;
}
.errorButton {
  height: 35px;
  border-radius: 5px;
  background: rgb(217, 91, 96);
  color: white;
  padding: 0 5px;
}
.header-btn {
  height: 56px;
  line-height: 56px;
  padding: 0 12px 0 16px;
  // background: #FAFAFA;
  color: red;
  font-weight: bold;
  border: 1px solid #eeeeee;
  cursor: pointer;
  -webkit-box-flex: 1;
  box-flex: 1;
  display: -webkit-box;
  display: flex;
  border-radius: 3px;
  font-size: 14px;
  border: none;
  justify-content: center;
  align-items: center;
  // margin-right: 3%;
}
.consumerAccess {
  width: 100%;
  height: 100vh;
  background: white;
  .topBanner {
    width: 100%;
    height: 6vh;
    border-bottom: 1px solid #ebebeb;
    position: fixed;
    top: 0;
    box-shadow: 0 1px 1px #ebebeb;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  .accessCon {
    width: 80%;
    .title {
      font-size: 18px;
      font-weight: bold;
      width: 100%;
      // height: 6rem;
    }
    .process {
      width: 100%;
      height: 4rem;
      .processName {
        font-size: 14px;
      }
      .processLine {
        padding: 0 20px;
      }
    }
    .rowLine {
      width: 100%;
      height: 2px;
      background: rgb(228, 228, 228);
    }
    .conBlock {
      width: 100%;
      height: 60vh;
      .shouquanBlock {
        width: 70%;
        height: 100%;
        flex-direction: column;
        margin-top: -80px;
        .shouTitle {
          font-size: 16px;
          padding: 30px 0;
          font-weight: bold;
        }
        .headImg {
          width: 100px;
          height: 100px;
          border-radius: 50%;
          img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
          }
        }
        .minTitle {
          font-size: 14px;
          padding: 20px 0;
        }
        .conDetail {
          line-height: 25px;
          font-size: 14px;
          i {
            margin-top: -2px;
          }
        }
        .warnCon {
          color: red;
          padding: 30px 0 0 0;
          margin-bottom: -15px;
        }
      }
      .codeBlock {
        width: 70%;
        height: 100%;
        .imgBlock {
          width: 35%;
          height: 45vh;
          padding: 0 30px;
          margin-top: -80px;
          img {
            width: 100%;
            height: 100%;
          }
          .imgTip {
            font-size: 12px;
            width: 100%;
            height: 4rem;
          }
        }
      }
      .warnBlock {
        widows: 30%;
        height: 90%;
        padding: 30px;
        border-left: 1px solid rgb(228, 228, 228);
        .warnTitle {
          font-size: 14px;
          padding: 0 10px;
        }
        .warnCon {
          font-size: 12px;
          line-height: 18px;
        }
      }
    }
    .buttonBlock {
      width: 100%;
      height: 3rem;
      padding: 50px 0;
    }
  }
  .input-wrapper {
    position: relative;
  }
  .input-wrapper .upload-input {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    opacity: 0;
  }
}
</style>
